#coding=utf-8

from datetime import *
import Core.Gadget as Gadgt


class DataSeries(object):

    def __init__(self, name):
        self.items = []
        self.name = name
        self.n = 0

    def Count(self):
        return self.items.__len__()

    def DateTime1(self):
        return self.GetDateTime(0)

    def DateTime2(self):
        return self.GetDateTime(self.Count()-1)

    def First(self):
        return self.items[0]

    def Last(self):
        if self.Count() == 0:
            return None
        return self.items[self.Count()-1]

    def __getitem__(self, item):
        if self.Count() < item or item < 0:
            return None
        return self.items[item]

    def __iter__(self):
        return self

    def __next__(self):
        if self.n < self.Count():
            item = self.GetByIndex(self.n)
            self.n = self.n + 1
            return item
        self.n = 0
        raise StopIteration()

    def Add(self, data):
        data["DataSeries"] = self.name
        self.items.append(data)
        self.n = self.n + 1

    def GetByIndex(self, index):
        return self.items[index]

    def Get(self, datetime, option="Previous", datetiemField="DateTime"):
        #if self.count() == 0:
        #    return None
        #index = self.getIndex(datetime,option)
        #if index == None:
        #    return None
        #return self.getByIndex(index)
        return Gadgt.Find(self.items, datetime, option, datetiemField)

    def GetDateTime(self, index):
        if index < 0 or index > self.items.__len__()-1:
            return None
        dt1 = self.items[index]["StdDateTime"]
        # datetime = self.items[index]["StdDateTime"] - timedelta(hours=-8) # 中国默认时区
        datetime = self.items[index]["StdDateTime"]
        # datetime = datetime.replace(tzinfo=None)
        return datetime

    def GetIndex(self, datetime,option="Previous"):
        return  Gadgt.FindIndex(self.items, datetime, option)

    def Print(self):
        for data in self.items:
            if "Value" in data:
                print(str(data["StdDateTime"]) + " " + str(data["Value"]))
            else:
                print(str(data["StdDateTime"]))

    @classmethod
    def ParseSymbol(self, dataSeriesName):
        names = dataSeriesName.split('_')
        return names[0]

    @classmethod
    def ParseDataType(self, dataSeriesName):
        names = dataSeriesName.split('_')
        return names[len(names)-1]

    @classmethod
    def ParseDataName(self, dataSeriesName):
        names = dataSeriesName.split('_')
        if len(names) >= 3:
            temp = []
            for i in range(1, len(names)-1):
                temp.append(names[i])
            name = "_".join(temp)
            return name
        else:
            return names[len(names)-2]

    @classmethod
    def ParseSize(self, dataSeriesName):
        names = dataSeriesName.split('_')
        if len(names) > 2:
            return int(names[2])
        return 0
